<?php
namespace app\common\service;;

use app\common\logic\OrderLogic;
use think\facade\Db;

/**
 * Class MyOrder
 * @package app\common\service
 * 我的订单
 */
class MyOrder extends Base {

    /**
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 订单列表数据
     */
    public function lists(){
        $page = input('page');
        //列表过滤器，生成查询Map对象
        $map = [];
        $map['user_id'] = $this->user_id;
        $status = input('st')?:'0';
        if($status==3){
            $map['order_status'] = ['in',[3,4]];
        }elseif($status!='all'){
            $map['order_status'] = $status;
        }


        //查询订单列表
        $field = 'order_id,order_sn,order_status,order_status,total_shop_price,s_user_id,shipping_name,delivery_no,sid,refund_id';
        $lists = Db::name('order')
            ->where($map)
            ->order('order_id desc')
            ->field($field)
            ->paginate(15,false,['page'=>$page,'list_rows'=>15]);
        if($lists->total()){
            foreach($lists as $k=>$v){
                $goods_list = Db::name('order_goods')
                    ->alias('og')
                    ->join('goods g','og.goods_id=g.goods_id')
                    ->where(['order_id'=>$v['order_id']])
                    ->field('og.goods_id,og.goods_name,og.goods_num,og.shop_price,og.spec_key_name,g.original_img,og.refund_id,og.refund_goods_id')
                    ->select()->toArray();
                $num_total = 0;
                if($goods_list){
                    foreach($goods_list as $kk=>$vv){
                        $goods_list[$kk]['image'] = $vv['original_img'];
                        $num_total = bcadd($num_total,$vv['goods_num']);
                    }
                }
                $v['num_total'] = (int)$num_total;
                $v['goods_list'] = $goods_list;
                if($v['sid']>0){
                    $supply_info = Db::name('suppliers')->where('id',$v['sid'])->find();
                }
                if(!$supply_info){
                    $supply_info = [
                        'name' => tpCache('basic.store_name'),
                        'logo' => tpCache('basic.store_logo'),
                    ];
                }
                if($v['refund_id']){
                    $refund_info = Db::name('order_refund')->where(['id'=>$v['refund_id']])->find();
                }else{
                    $refund_info = [];
                }
                $v['refund_info'] = $refund_info;

                $v['supply_info'] = $supply_info;
                $v['order_can_refund'] = tpCache('shop.canrefund');
                $lists->offsetSet($k,$v);
            }
        }

        $shopset = [
            'comment' => tpCache('shop.comment'),
            'canrefund' => tpCache('shop.canrefund'),
        ];
        $result = [
            'status' => true,
            'msg' => '',
            'data' => $lists,
            'canrefund' => 1,
            'shopset' => $shopset
        ];
        return $result;
    }

    /**
     * 订单详情
     */
    public function detail(){
        $id = input('order_id');
        $map = [];
        $map['order_id'] = $id;
        $map['user_id'] = $this->user_id;

        $order_info = Db::name('order')
            ->where($map)
            ->field('order_id,username,add_time,user_note,shipping_name,invoice_no,
            shipping_price,total_shop_price,order_sn,add_time,order_status,consignee,
            pay_time,shipping_time,confirm_time,mobile,total_shop_price,province,city,district,address,payment,leixing_id,shipping_code,shipping_name,delivery_no,refund_status')
            ->find();
        if (!$order_info) {
            $result = [
                'status' => true,
                'msg' => '没有获取到订单信息',
                'data' => []
            ];
            return $result;
        }
        $leixing_arr = Db::name('goods_leixing')->where('1=1')->column('name','id');
        $order_info['leixing_name'] = $leixing_arr[$order_info['leixing_id']];
        $order_info['add_time'] = date('Y-m-d H:i:s',$order_info['add_time']);
        $order_info['pay_time'] = date('Y-m-d H:i:s',$order_info['pay_time']);
        $order_info['shipping_time'] = date('Y-m-d H:i:s',$order_info['shipping_time']);
        $order_info['confirm_time'] = date('Y-m-d H:i:s',$order_info['confirm_time']);

        $order_info['real_username'] = $order_info['username'];
        $order_info['order_can_refund'] = 1;
        //所有商品都已经申请退款了，不再能申请
        $refund_count = Db::name('order_goods')->where('order_id',$order_info['order_id'])->where('refund_goods_id',0)->count();
        if($refund_count==0){
            $order_info['order_can_refund'] = 0;
        }

        $goods_list = Db::name('order_goods')
            ->alias('og')
            ->join('goods g','og.goods_id=g.goods_id')
            ->where(['order_id'=>$order_info['order_id']])
            ->field('og.rec_id,og.goods_id,og.goods_name,og.goods_num,og.shop_price,og.spec_key_name,g.original_img,og.refund_goods_id')
            ->select()->toArray();
        if($goods_list){
            foreach($goods_list as $kk=>$vv){
                $goods_list[$kk]['image'] = $vv['original_img'];
                if($vv['refund_goods_id']>0){
                    $refund_goods = Db::name('order_refund_goods')->where(['id'=>$vv['refund_goods_id']])->find();
                    $goods_list[$kk]['refund_status'] = $refund_goods['status'];
                }else{
                    $goods_list[$kk]['refund_status'] = -1;
                }
            }
        }
        $order_info['goods_list'] = $goods_list;
        $province = Db::name('region')->where(array('id'=>$order_info['province']))->value('name');
        $city =  Db::name('region')->where(array('id'=>$order_info['city']))->value('name');
        $district =  Db::name('region')->where(array('id'=>$order_info['district']))->value('name');
        $full_address = $province.' '.$city.' '.$district.' '. $order_info['address'];
        $order_info['full_address'] = $full_address;
        $order_status_arr = logic('OrderLogic')->getStatus();
        $order_info['status_name'] = $order_status_arr[$order_info['order_status']];

        $shopset = [
            'comment' => tpCache('shop.comment'),
            'canrefund' => tpCache('shop.canrefund'),
        ];
        $result = [
            'status' => true,
            'msg' => '',
            'data' => $order_info,
            'shopset' => $shopset
        ];
        return $result;
    }

    /**
     * 删除订单
     */
    public function delOrder(){
        $id = input('order_id');
        //检查是否有积分，余额支付
        $logic = new OrderLogic();
        Db::startTrans();
        $data = $logic->cancel_order($this->user_id, $id);
        if($data['status']!=1){
            Db::rollback();
            $result = [
                'status' => true,
                'msg' => $data['msg'],
                'data' => []
            ];
            return $result;
        }
        Db::commit();
        $shop_set = self::$shop_set;
        $result = [
            'status' => true,
            'msg' => '删除成功！',
            'data' => [],
            'shoppset' => $shop_set
        ];
        return $result;
    }

    /**
     * 订单统计
     */
    public function orderCount(){
        //列表过滤器，生成查询Map对象
        $map = [];
        $map['user_id'] = $this->user_id;

        //查询订单列表
        $field = 'count(order_id),order_status';
        $data = [];
        //待支付
        $data['no_pay'] = Db::name('order')->where(['user_id'=>$this->user_id,'order_status'=>0])->count();
        //已支付
        $data['have_pay'] = Db::name('order')->where(['user_id'=>$this->user_id,'order_status'=>1])->count();
        //待收货
        $data['wait_receive'] = Db::name('order')->where(['user_id'=>$this->user_id,'order_status'=>2])->count();
        //已完成
        $data['over'] = Db::name('order')->where(['user_id'=>$this->user_id,'order_status'=>3])->count();

        $result = [
            'status' => true,
            'msg' => '',
            'data' => $data
        ];
        return $result;
    }

    public function confirmOrder(){
        $id = input('order_id');
        Db::startTrans();
        $data = logic('OrderLogic')->confirm_order($id, $this->user_id);
        if($data['status']!=1){
            Db::rollback();
            $result = [
                'status' => false,
                'msg' => $data['msg'],
                'data' => ''
            ];
            return $result;
        }
        Db::commit();
        $result = [
            'status' => true,
            'msg' => '操作成功！',
            'data' => ''
        ];
        return $result;
    }

    public function logistics(){
        $order_id = input('order_id');
        $order_info = Db::name('order')->where('order_id',$order_id)->find();
        //查询物流信息
        $res = logic('OrderLogic')->getLogistics($order_info['shipping_code'],$order_info['delivery_no']);
        if($res && $res['status']=='200'){
            $result = [
                'status' => 1,
                'datalist' => $res['data'],
                'express_com' => $order_info['shipping_name'],
                'express_no' => $order_info['delivery_no'],
            ];
        }else{
            $result = [
                'status' => 0,
                'datalist' => [],
                'msg' => $res['message'],
                'express_com' => $order_info['shipping_name'],
                'express_no' => $order_info['delivery_no'],
            ];
        }
        return $result;
    }

    //退款选择
    public function refundinit(){
        $id = input('id');
        $detail = Db::name('order')->where('order_id',$id)->where('user_id',$this->user_id)->find();
        $where = [];
        $where[] = ['og.order_id','=',$id];
        if(input('ogid')){
            $where[] = ['og.rec_id','=',input('ogid')];
        }
        $where[] = ['og.refund_goods_id','=',0];
        $prolist = Db::name('order_goods')
            ->alias('og')
            ->join('goods g','og.goods_id=g.goods_id')
            ->where($where)
            ->field('og.*,g.goods_name,g.original_img')
            ->select();
        $storeinfo = Db::name('suppliers')->where('id',$detail['s_user_id'])->find();
        $shopset = self::$shop_set;
        if($detail['order_status']==1){
            $type = 0;
        }else{
            $type = 1;
        }
        $map = [];
        $map[] = ['status','=',1];
        $map[] = ['type','=',$type];
        $refund_reasons = Db::name('refund_reason')
            ->where($map)
            ->order('sort desc,id desc ')
            ->column('name');
        $rdata = [];
        $rdata['status'] = 1;
        $rdata['detail'] = $detail;
        $rdata['prolist'] = $prolist;
        $rdata['shopset'] = $shopset;
        $rdata['storeinfo'] = $storeinfo;
        $rdata['refund_reasons'] = $refund_reasons;
        return $rdata;
    }
    //申请退货
    public function apply_refund(){
        $id = input('order_id');
        $gids = input('og_ids/a');
        $reason = input('reason');
        $remark = input('remark');
        $pics = input('content_pic/a');
        if($reason==''){
            return ['status'=>0,'msg'=>'请输入退货原因'];
        }
        Db::startTrans();
        $order_info = Db::name('order')->where('order_id',$id)->find();

        //添加退款记录
        $refund = [];
        $refund['user_id'] = $order_info['user_id'];
        $refund['ps_user_id'] = $order_info['ps_user_id'];
        $refund['refund_no'] = logic('OrderLogic')->get_order_sn();
        $refund['order_id'] = $id;
        $refund['reason'] = $reason;
        $refund['remark'] = $remark;
        $refund['pics'] = implode(',',$pics);
        $refund['w_time'] = time();
        $rid = Db::name('order_refund')->insertGetId($refund);
        //更新订单状态
        $save = [];
        $save['refund_id'] = $rid;
        $rs = Db::name('order')->where(['order_id'=>$id])->update($save);
        $map = [];
        $map[] = ['order_id','=',$id];
        if($gids){
            $map[] = ['rec_id','in',$gids];
        }
        $og_list = Db::name('order_goods')->where($map)->select()->toArray();
        foreach($og_list as $og){
            $refund_goods = [];
            $refund_goods['ps_user_id'] = $order_info['ps_user_id'];
            $refund_goods['refund_id'] = $rid;
            $refund_goods['order_id'] = $id;
            $refund_goods['og_id'] = $og['rec_id'];
            $refund_goods['goods_id'] = $og['goods_id'];
            $refund_goods['spec_goods_id'] = $og['spec_goods_id'];
            $refund_goods['shop_price'] = $og['shop_price'];
            $refund_goods['num'] = $og['goods_num'];
            $refund_goods['w_time'] = time();
            $rgid = Db::name('order_refund_goods')->insertGetId($refund_goods);
            $rs = Db::name('order_goods')->where('rec_id','=',$og['rec_id'])
                ->update(['refund_id'=>$rid,'refund_goods_id'=>$rgid]);
        }
        if($rs){
            Db::commit();
            return ['status'=>1,'msg'=>'申请成功，请耐心等待平台审核'];
        }else{
            Db::rollback();
            return ['status'=>0,'msg'=>'更新订单状态失败，请联系客服处理'];
        }
    }

    public function comment()
    {
        $params = input();
        $og = Db::name('order_goods')->where('rec_id',input('ogid'))->find();
        $good_info = Db::name('goods')->where('goods_id',$og['goods_id'])->find();
        $comment = Db::name('comment')->where('rec_id',input('ogid'))->find();
        //$comment['content_pic'] = explode(',', $comment['img']);
        $result = [
            'status' => true,
            'msg' => '',
            'og' => $good_info,
            'comment' => $comment,
        ];
        return $result;

    }
    /**
     *添加评论
     */
    public function add_comment()
    {
        $params = input();
        $ogid = input('ogid');
        $goods_info = Db::name('order_goods')->where('rec_id',$ogid)->find();
        $add = [];
        $add['img'] = $params['content_pic']??'';
        $user_info = $this->user;
        $add['rec_id'] = $ogid;
        $add['goods_id'] = $goods_info['goods_id']??0;
        $hide_username = $params['hide_username']??0;
        if (empty($hide_username)) {
            $add['username'] = $user_info['nickname']?:$user_info['username'];
        }
        $add['is_anonymous'] = $hide_username;  //是否匿名评价:0不是\1是
        $add['order_id'] = $goods_info['order_id'];
//        $add['service_rank'] = $params['service_rank']??5;
//        $add['deliver_rank'] = $params['deliver_rank']??5;
        $add['goods_rank'] = $params['score'];
        $add['supply_rank'] = $params['score'];
        $add['is_show'] = 0; //默认显示
        //$add['content'] = htmlspecialchars(I('post.content'));
        $add['content'] = $params['content'];
        $add['w_time'] = time();
        $add['ip_address'] = request()->ip();
        $add['user_id'] = $this->user_id;
        $add['add_time'] = time();
        $add['sid'] = $goods_info['sid'];
        //添加评论
        $row = logic('OrderLogic')->add_comment($add);
        if ($row['status'] == 1) {
            return $row;
        } else {
            return ['status'=>0,'msg'=>$row['msg']];
        }

    }
    //评论商家
    public function comment_supply(){
        $params = input();
        $order_info = Db::name('order')->where('order_id',input('orderid'))->find();
        if($order_info['sid']){
            $supply = Db::name('suppliers')->where('id',$order_info['sid'])->find();
        }else{
            $supply = [
                'name' => tpCache('basic.store_name'),
                'logo' => tpCache('basic.store_logo')
            ];
        }
        $order_goods =  Db::name('order_goods')
            ->alias('og')
            ->join('goods g','og.goods_id=g.goods_id')
            ->where(['order_id'=>input('orderid')])
            ->where(['og.is_comment'=>0])
            ->field('og.goods_id,og.goods_name,og.goods_num,og.shop_price,og.spec_key_name,g.original_img')
            ->select();
        $result = [
            'status' => true,
            'msg' => '',
            'supply' => $supply,
            'order_info' => $order_info,
            'order_goods' => $order_goods
        ];
        return $result;
    }
    public function add_comment_supply()
    {
        Db::startTrans();
        $params = input();
        $ogid = input('orderid');
        $order_info = Db::name('order')->where('order_id',input('orderid'))->find();
        $supply = Db::name('suppliers')->where('id',$order_info['sid'])->find();
        $add = [];
        $add['img'] = $params['content_pic']??'';
        $user_info = $this->user;
        $add['rec_id'] = I('rec_id/d');
        $add['goods_id'] = $goods_info['goods_id']??0;
        $hide_username = $params['hide_username']??0;
        if (empty($hide_username)) {
            $add['username'] = $user_info['nickname'];
        }
        $add['is_anonymous'] = $hide_username;  //是否匿名评价:0不是\1是
        $add['order_id'] = $goods_info['order_id'];
//        $add['service_rank'] = $params['service_rank']??5;
//        $add['deliver_rank'] = $params['deliver_rank']??5;
//        $add['goods_rank'] = $params['score'];
        $add['supply_rank'] = $params['score_dp'];
        $add['is_show'] = 0; //默认显示
        //$add['content'] = htmlspecialchars(I('post.content'));
        $add['content'] = $params['content'];
        $add['w_time'] = time();
        $add['ip_address'] = request()->ip();
        $add['user_id'] = $this->user_id;
        $add['sid'] = $order_info['sid'];
        //添加评论
        $row = logic('OrderLogic')->add_comment_supply($add);

        //添加商品评论
        $goods_lists = Db::name('order_goods')->where('order_id',$order_info['order_id'])->select();
        foreach($goods_lists as $goods_info){
            $add = [];
            $add['img'] = $params['content_pic']??'';
            $user_info = $this->user;
            $add['rec_id'] = $goods_info['rec_id'];
            $add['goods_id'] = $goods_info['goods_id']??0;
            $hide_username = $params['hide_username']??0;
            if (empty($hide_username)) {
                $add['username'] = $user_info['nickname']?:$user_info['username'];
            }
            $add['is_anonymous'] = $hide_username;  //是否匿名评价:0不是\1是
            $add['order_id'] = $goods_info['order_id'];
//        $add['service_rank'] = $params['service_rank']??5;
//        $add['deliver_rank'] = $params['deliver_rank']??5;
            $add['goods_rank'] = $params['score'];
            $add['supply_rank'] = $params['score'];
            $add['is_show'] = 0; //默认显示
            //$add['content'] = htmlspecialchars(I('post.content'));
            $add['content'] = $params['content'];
            $add['w_time'] = time();
            $add['ip_address'] = request()->ip();
            $add['user_id'] = $this->user_id;
            $add['add_time'] = time();
            $add['sid'] = $goods_info['sid'];
            //添加评论
            $row = logic('OrderLogic')->add_comment($add);
        }
        Db::commit();
        if ($row['status'] == 1) {
            return $row;
        } else {
            return ['status'=>0,'msg'=>$row['msg']];
        }

    }

    //退款列表
    public function refundlists(){
        $page = input('page');
        //列表过滤器，生成查询Map对象
        $map = [];
        $map['r.user_id'] = $this->user_id;
        $status = input('st')?:'all';
        if($status==1){
            $map[] = ['r.status','=',0];
        }
        if($status==2){
            $map[] = ['r.status','in',[1,2]];
        }
        if($status==3){
            $map[] = ['r.status','=',3];
        }
        //查询订单列表
        $field = 'o.order_id,order_sn,o.order_status,total_shop_price,sid,r.status,r.w_time,r.reason,r.id';
        $lists = Db::name('order_refund')
            ->alias('r')
            ->join('order o','r.order_id=o.order_id')
            ->where($map)
            ->order('o.order_id desc')
            ->field($field)
            ->paginate(15,false,['page'=>$page,'list_rows'=>15]);
        if($lists->total()){
            foreach($lists as $k=>$v){
                $goods_list = Db::name('order_goods')
                    ->alias('og')
                    ->join('goods g','og.goods_id=g.goods_id')
                    ->where(['refund_id'=>$v['id']])
                    ->field('og.goods_id,og.goods_name,og.goods_num,og.shop_price,og.spec_key_name,g.original_img')
                    ->select()->toArray();
                $num_total = 0;
                if($goods_list){
                    foreach($goods_list as $kk=>$vv){
                        $goods_list[$kk]['image'] = $vv['original_img'];
                        $num_total = bcadd($num_total,$vv['goods_num']);
                    }
                }
                $v['num_total'] = $num_total;
                $v['goods_list'] = $goods_list;
                $supply_info = Db::name('suppliers')->where('id',$v['sid'])->find();
                $v['supply_info'] = $supply_info;
                $lists->offsetSet($k,$v);
            }
        }

        $result = [
            'status' => true,
            'msg' => '',
            'data' => $lists->items(),
        ];
        return $result;
    }
    //退款详情
    public function refund_detail(){
        $id = input('id');
        $map = [];
        $map['r.user_id'] = $this->user_id;
        $map['r.id'] = $id;
        $field = 'o.order_id,order_sn,order_status,order_status,total_shop_price,s_user_id,r.status,r.w_time,r.reason,r.w_time,r.refund_no,r.remark,r.pics';
        $info = Db::name('order_refund')
            ->alias('r')
            ->join('order o','r.order_id=o.order_id')
            ->where($map)
            ->order('o.order_id desc')
            ->field($field)
            ->find();
        $info['pics'] = explode(',',$info['pics']);
        $info['w_time'] = date('Y-m-d H:i:s',$info['w_time']);
        $og_ids = Db::name('order_refund_goods')->where(['refund_id'=>$id])->column('og_id');
        $goods_list = Db::name('order_goods')
            ->alias('og')
            ->join('goods g','og.goods_id=g.goods_id')
            ->where('order_id',$info['order_id'])
            ->where('rec_id','in',$og_ids)
            ->field('og.goods_id,og.goods_name,og.goods_num,og.shop_price,og.spec_key_name,g.original_img')
            ->select();
        $info['goods_list'] = $goods_list;
        $result = [
            'status' => true,
            'msg' => '',
            'data' => $info,
        ];
        return $result;
    }
}
